import { App, Form, Button, Input, Checkbox } from 'antd'
import { ImportantEditModal } from '@/desktop/components'
import services from '@/services'
import { ContactType } from '@/services/contacts'
import type { CustomSidebar } from '@/services/features/chat-sidebars'

export function Edit(props: { editing: true | CustomSidebar | null; onFinish: () => void }) {
  const { editing, onFinish } = props
  return <ImportantEditModal
    title={editing === true ? '添加侧边栏' : '编辑侧边栏'}
    width="600px"
    open={editing !== null}
    onCancel={onFinish}
  >
    {editing !== null ? (
      <EditContent item={editing === true ? undefined : editing} onFinish={onFinish} />
    ) : null}
  </ImportantEditModal>
}

type EditSideBar = Pick<CustomSidebar, 'name' | 'url' | 'scope'>

function EditContent(props: { item?: CustomSidebar; onFinish: () => void }) {
  const { message } = App.useApp()
  const { item, onFinish } = props

  const initialValues: Partial<EditSideBar> = item ? { ...item } : { scope: [ContactType.external] }

  const [saving, setSaving] = useState(false)
  async function save(values: EditSideBar) {
    const data = {
      ...(item ? item : ({ system: false, disabled: false } as const)),
      name: values.name.trim(),
      url: values.url.trim(),
      scope: values.scope,
    }

    setSaving(true)
    const res = await services.features.chatSidebars.addOrUpdate(data)
    setSaving(false)
    if (res.success) {
      void message.success('保存成功')
      onFinish()
    } else {
      void message.warning(`保存失败：${res.error}`)
    }
  }

  return <Form initialValues={initialValues} labelCol={{ span: 4 }} onFinish={save}>
    <main>
      <Form.Item name="name" label="页面名称" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item name="url" label="页面 URL" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item name="scope" label="范围" rules={[{ required: true, message: '请选择范围' }]}>
        <Checkbox.Group>
          <Checkbox value={ContactType.external}>客户</Checkbox>
          <Checkbox value={ContactType.group}>群</Checkbox>
          <Checkbox value={ContactType.internal}>员工</Checkbox>
        </Checkbox.Group>
      </Form.Item>
    </main>
    <footer>
      <Button onClick={onFinish}>取消</Button>
      <Button type="primary" htmlType="submit" loading={saving}>
        保存
      </Button>
    </footer>
  </Form>
}
